<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片区域  -->
 <el-card>
   <!-- 搜索与添加 -->
   <el-row :gutter="20">
     <el-col :span="8">
   <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="getUserList()">
    <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
   </el-input>
     </el-col>
     <el-col :span="4">
       <el-button type=primary  @click="dialogVisible = true">添加用户</el-button>
     </el-col>
  </el-row>
       <!--userlist -->
       <el-table
      :data="userlist"
      stripe
      style="width: 100%">
      <!-- 添加索引列 -->
      <el-table-column
        type="index"
        label="序号"
        width="120">
        </el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        width="120">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮件"
        width="120">
      </el-table-column>
      <el-table-column
        prop="id"
        label="编号"
        width="120">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="手机号"
        width="120">
      </el-table-column>
      <el-table-column
        prop="mg_state"
        label="状态"
        width="120">
        <!-- 作用域插槽渲染状态列 -->
        <template slot-scope="scope">
          <!-- {{scope.row}} -->
          <!-- 开关根据v-model的true还是false渲染scope.row获取该行数据， -->
          <el-switch
  v-model="scope.row.mg_state"
  @change="userStateChange(scope.row)"
  >
</el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色名"
        width="120">
      </el-table-column>
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditdialog(scope.row.id)"></el-button>
<el-button type="danger" icon="el-icon-delete" size="mini" @click="deletebyid(scope.row.id)"></el-button>
 <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
      <el-button type="warning" icon="el-icon-setting" size="mini" @click="setroledialog(scope.row)"></el-button>
    </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页区  -->
<el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryParams.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>
<!-- 添加用户对话框 -->
<el-dialog
  title="添加用户"
  :visible.sync="dialogVisible"
  width="50%"
  @close="resetaddForm">
  <el-form :model="addForm"  ref="addFormRef" label-width="100px">
  <el-form-item label="用户名称" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机号" prop="phonenumber">
    <el-input v-model="addForm.phonenumber"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="adduser">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改用户信息对话框 -->
<el-dialog
  title="修改用户"
  :visible.sync="editdialogVisible"
  width="50%"
  @close="reseteditForm">
  <el-form :model="editForm" ref="editFormRef" label-width="100px">
  <el-form-item label="用户名称" >
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱号" >
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机号">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>
  </el-form>
   <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="edituser">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配角色的对话框 -->
<el-dialog
  title="分配角色"
  :visible.sync="etroledialogvisible"
  width="50%"
  @close="resetuserrole">
  <div>
    <p>当前的用户:{{userInfo.username}}</p>
    <p>当前的角色:{{userInfo.role_name}}</p>
    <p>分配新角色
      <el-select v-model="value" placeholder="请选择角色">
    <el-option
      v-for="item in rolelist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="etroledialogvisible = false">取 消</el-button>
    <el-button type="primary" @click="etrole" >确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 获取用户列表的参数对象
      queryParams: {
        query: '',
        // 获取第几页、当前页数（分页中）
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 3
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      editdialogVisible: false,
      addForm: {},
      addFormRule: {
        username: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { min: 3, max: 17, message: '长度为7 到 17字符', trigger: 'blur' }],
        phonenumber: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 3, max: 11, message: '长度为 11个字符', trigger: 'blur' }]
      },
      editForm: {},
      etroledialogvisible: false,
      // 被分配角色的信息
      userInfo: {},
      // 所有角色的列表
      rolelist: [],
      // 分配新角色时下拉菜单传入选中的的值
      value: ''

    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryParams })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.erro(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // pagesize改变时的事件
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.queryParams.pagesize = val
      this.getUserList()
    },
    // 当前页码变化时的事件
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.queryParams.pagenum = val
      this.getUserList()
    },
    // 监听Switch开关的改变
    async userStateChange (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      console.log(res)
      // if (res.meta.status !== 200) {
      //   userInfo.mg_state = !userInfo.mg_state
      //   // return this.$message.erro(res.meta.msg)
      // }
      // this.$message.sucess(res.meta.msg)
    },
    // 关闭添加用户对话框时重置表单
    resetaddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    adduser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) return
        this.dialogVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 修改用户信息
    // 点击修改时根据id获取用户信息
    async showeditdialog (id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      this.editForm = res.data
    },
    reseteditForm () {
      this.$refs.editFormRef.resetFields()
    },
    async edituser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        // console.log(res)
        if (res.meta.status !== 200) return
        this.editdialogVisible = false
        // 创新获取用户列表
        this.getUserList()
      })
    },
    // 根据id删除用户信息
    // 返回值为一个promise对象，确定返回confirm，取消返回err
    async deletebyid (id) {
      const deleteresult = await
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '取消删除'
        // })
      })
      if (deleteresult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '取消删除'
        })
      }
      // await 不允许嵌套在then函数里面，所以写在外面
      const { data: res } = await this.$http.delete('users/' + id)
      // 不允许删除admin账户
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({
          type: 'info',
          message: '删除失败'
        })
      }
      // 重新获取用户列表
      this.getUserList()
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    // 获取数据对话框（用户信息，所有角色列表）
    async setroledialog (userInfo) {
      this.etroledialogvisible = true
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      this.rolelist = res.data
    },
    // 重新分配角色
    async etrole () {
      if (!this.value) {
        return this.$message({
          type: 'info',
          message: '取消删除'
        })
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.value })
      console.log(res)
      this.getUserList()
      this.etroledialogvisible = false
    },
    resetuserrole () {
      // eslint-disable-next-line no-unused-expressions
      this.userInfo = []
      this.value = ''
    }
  }
}
</script>
<style lang="less" scoped>

</style>
